﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace Joyeon.Helpers
{
    /// <summary>
    /// 读取中文和对应的拼音放入Key-Value字典中，以供根据汉字查询拼音，生成简称。
    /// </summary>
    public class ShortNameMappingHelper
    {
        private NameValueCollection mapping = new NameValueCollection();
        private static ShortNameMappingHelper instance = null;

        public static void Init()
        {
            if (instance == null)
            {
                instance = new ShortNameMappingHelper();
            }
        }
        /// <summary>
        /// 根据汉字获得拼音的首字母
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public static string GetShortName(string title)
        {
            if (instance == null)
            {
                instance = new ShortNameMappingHelper();
            }

            if (title == null || title == "") return "";

            string shortname = "";
            for(int i=0; i<title.Length; i++)
            {
                string subTitle = title.Substring(i, 1);
                string subShortname = instance.mapping.Get(subTitle);

                if (subShortname == null || subShortname.Length == 0)
                {
                    subShortname = subTitle;
                }
                else
                {
                    subShortname = subShortname.Substring(0,1);
                }

                shortname = shortname + subShortname;
            }
            return shortname;
        }


        private ShortNameMappingHelper()
        {
            String path = "ChineseDictionary.dic";
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            using(System.IO.StreamReader reader = new System.IO.StreamReader(fs,Encoding.UTF8,false))
            {
                String line = reader.ReadToEnd();
                if (line==null)
                {
                    return;
                }
                String[] array = line.Split('\n');
                int length = array.Length;
                for (int i = 0; i < length; i++)
                {
                    String[] cell = array[i].Split(':');
                    if (cell!=null&&cell.Length==2)
                    {
                        mapping.Add(cell[0],cell[1]);
                    }
                }
                
            }
        }

    }
}
